package com.zhy.sunmi.fragment.sell;

import android.app.Dialog;
import android.content.Context;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import rx.observers.SafeSubscriber;

import com.google.gson.Gson;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.greendao.gen.SellGoodHistoryDao;
import com.zhy.greendao.gen.SoldGoodDetailDao;
import com.zhy.sunmi.MyApplication;
import com.zhy.sunmi.PrintUtil4;
import com.zhy.sunmi.R;
import com.zhy.sunmi.bean.SellGoodHistory;
import com.zhy.sunmi.bean.SellingGood;
import com.zhy.sunmi.bean.SocketErrorBean;
import com.zhy.sunmi.bean.SocketLogBean;
import com.zhy.sunmi.bean.SocketSuccessBean;
import com.zhy.sunmi.bean.SoldGoodDetail;
import com.zhy.sunmi.myView.MyPresentation;
import com.zhy.sunmi.utils.ScreenUtils;
import com.zhy.sunmi.utils.XMathUtil;
import com.zhy.sunmi.utils.network.ProgressSubscriber;
import com.zhy.sunmi.utils.network.RetrofitUtil;

import org.java_websocket.client.WebSocketClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.zhy.sunmi.MyApplication.pos_usb;
import static com.zhy.sunmi.fragment.sell.SubSellFragment.getSecondTimestamp;
import static com.zhy.sunmi.utils.PrintUtil.cutPaper;
import static com.zhy.sunmi.utils.PrintUtil.printBar;
import static com.zhy.sunmi.utils.PrintUtil.printText;


public class SubPayFragment extends Fragment {

//    private String url = "wss://sy876r670000.test.connect.paymentsense.cloud/pac?token=12164861-bcae-4ce4-9ac4-338b9048f26c&api-version=v1&software-house-id=spxus&installer-id=001";
    private String url = MyApplication.getInstance().getUrl();
    private WebSocketClient webSocketClient=MyApplication.getInstance().getWebSocketClient();
    private TextView tv;
    private StringBuilder sb = new StringBuilder();
    private static String TAG = "Socket";

    private RecyclerView recyclerView;
    private List<SellingGood> sellgoods = new ArrayList<>();
    private SellGoodHistoryDao sellGoodHistoryDao = MyApplication.getDaoSession().getSellGoodHistoryDao();
    private SoldGoodDetailDao soldGoodDetailDao = MyApplication.getDaoSession().getSoldGoodDetailDao();
    List<SoldGoodDetail> soldGoodDetailList = new ArrayList<>();

    private TextView bt_return;
    private TextView tv_cash;
    private TextView tv_card;
    private TextView tv_alipay;
    private TextView tv_wechat;
    private TextView tv_discount;
    private TextView tv_totalvat;
    private TextView bt_finish;
    private TextView tv_totalmoney;
    private String wjj;
    private String dis;
    private String vat = "0.00";
    private String totalmoney;
    View view;
    private AlertDialog dialogA;
    private SellGoodHistory sellGoodHistory;
//    private MyPresentation myPresentation;
    private TextView tv_confirm_card;
    private TextView tv_cancel_card;
     AlertDialog cardDialog;
    TextView tv_msg;
    long id;

    public SubPayFragment() {
        // Required empty public constructor
    }

    public void hiddenButton(){
        tv_wechat.setVisibility(View.INVISIBLE);
        tv_alipay.setVisibility(View.INVISIBLE);
        tv_cash.setVisibility(View.INVISIBLE);
        tv_card.setVisibility(View.INVISIBLE);
    }
    public void showButton(){
        tv_wechat.setVisibility(View.INVISIBLE);
        tv_alipay.setVisibility(View.INVISIBLE);
        tv_cash.setVisibility(View.VISIBLE);
        tv_card.setVisibility(View.VISIBLE);
        bt_finish.setVisibility(View.INVISIBLE);
        bt_return.setVisibility(View.VISIBLE);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment


        if (view == null) {
            view = inflater.inflate(R.layout.fragment_sub_pay, container, false);
            initView(view);
//            showDisplayByDisplayManager();
//            url=MyApplication.getInstance().getUrl();
//            URI serverURI = URI.create(url);

//            webSocketClient = new WebSocketClient(serverURI) {
//                @Override
//                public void onOpen(ServerHandshake handshakedata) {
//                    Log.d(TAG, "onOpen");
//                }
//
//                @Override
//                public void onMessage(String message) {
//                    Message handlerMessage = Message.obtain();
//                    handlerMessage.obj = message;
//                    handler.sendMessage(handlerMessage);
//
//                }
//
//                @Override
//                public void onClose(int code, String reason, boolean remote) {
//                    Log.d(TAG, "onClose");
//                }
//
//                @Override
//                public void onError(Exception ex) {
//                    Log.d(TAG, "onError");
//                webSocketClient.close();
////                webSocketClient.connect();
//                }
//
//
//            };
//            webSocketClient.connect();

        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        MyApplication.getInstance().setHandler(handler);
        return view;

    }

    @Override
    public void onResume() {
        super.onResume();

    }


//    void getCoupons2(String api_token) {
//        RetrofitUtil.getInstance().getCoupons2(new ProgressSubscriber<>(a->{
//
//        },getActivity()),api_token,"1");
//    }

    private void initView(View view) {
        bt_return = view.findViewById(R.id.bt_return);
        bt_finish = view.findViewById(R.id.bt_finish);
        bt_finish.setVisibility(View.INVISIBLE);
        tv_discount = view.findViewById(R.id.tv_discount);
        tv_totalvat = view.findViewById(R.id.tv_vat);
        tv_totalmoney = view.findViewById(R.id.tv_total_money);
        bt_return.setOnClickListener(v -> {
            SubSellingFragment subSellingFragment = (SubSellingFragment) getParentFragment();
            subSellingFragment.goShopping(0, null, null);

        });

        bt_finish.setOnClickListener(v -> {
            SubSellingFragment subSellingFragment = (SubSellingFragment) getParentFragment();
            subSellingFragment.goShopping(0, null, "return");
            bt_finish.setVisibility(View.INVISIBLE);
            showButton();
        });
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(new CommonAdapter<SoldGoodDetail>(getContext(), R.layout.item_selling_good, soldGoodDetailList) {

            @Override
            protected void convert(ViewHolder holder, SoldGoodDetail sellingGood, int position) {
                holder.setText(R.id.selling_number, sellingGood.getNumber() + "");
                holder.setVisible(R.id.iv_ljt, false);
                holder.setText(R.id.tv_good_disoff, new Double(sellingGood.getDiscount()).intValue() + "%");
                holder.setText(R.id.tv_selling_money, "£" + BigDecimal.valueOf(sellingGood.getTotalPrice()).setScale(2, BigDecimal.ROUND_DOWN).toString());
                holder.setText(R.id.tv_goodname, sellingGood.getEnglishName());
                holder.setText(R.id.tv_goodCname, sellingGood.getChineseName());

            }
        });
        tv_cash = view.findViewById(R.id.tv_cash);
        tv_alipay = view.findViewById(R.id.tv_alipay);
        tv_wechat = view.findViewById(R.id.tv_wechat);
        tv_cash.setOnClickListener(v -> {

            showDialog();
        });

        tv_card = view.findViewById(R.id.tv_card);
        tv_card.setOnClickListener(v -> {
            String a=sellGoodHistory.getTotalMoneyAfterDiscount();
            BigDecimal  aa= XMathUtil.multiply(new BigDecimal(a),new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);;
            String tid=MyApplication.getInstance().getTid();
            id=System.currentTimeMillis();
//            id=0;
//            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"sale\", \"params\": { \"tid\": \"VCMSPXUSIP0\", \"currency\": \"GBP\", \"amount\":"+aa+" },\"id\": 0 }";
//            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"sale\", \"params\": { \"tid\": \""+tid+"\", \"currency\": \"GBP\", \"amount\":"+aa+" },\"id\":"+id+" }";
//            if(MyApplication.getInstance().getWebSocketClient().isOpen()){
//                MyApplication.getInstance().getWebSocketClient().send(str);
                showDialog3();
//            }else {
////                Toast.makeText(getContext(),"error",Toast.LENGTH_SHORT).show();
//                showDialogError();
//                MyApplication.getInstance().initCardPay();
//            }
        });


//        view.findViewById(R.id.tv_cardrefund).setOnClickListener(v -> {
//            String a=sellGoodHistory.getTotalMoneyAfterDiscount();
//            BigDecimal  aa= XMathUtil.multiply(new BigDecimal(a),new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);;
//            String tid=MyApplication.getInstance().getTid();
////            long id2=0;
//            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"refund\", \"params\": { \"tid\": \""+tid+"\", \"currency\": \"GBP\", \"amount\":"+aa+" },\"id\":"+id+" }";
//            if(MyApplication.getInstance().getWebSocketClient().isOpen()){
//                webSocketClient.send(str);
//                showDialog3();
//            }else {
////                Toast.makeText(getContext(),"error",Toast.LENGTH_SHORT).show();
//                showDialogError();
//                webSocketClient.connect();
//            }
//        });




        tv_alipay.setOnClickListener(v -> {
//            String a=sellGoodHistory.getTotalMoneyAfterDiscount();
//            BigDecimal  aa= XMathUtil.multiply(new BigDecimal(a),new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);;
//            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"sale\", \"params\": { \"tid\": \"VCMSPXUTIP0\", \"currency\": \"GBP\", \"amount\":"+aa+" },\"id\": 0 }";
//            if(MyApplication.getInstance().getWebSocketClient().isOpen()){
//                webSocketClient.send(str);
//                showDialog3();
//            }
        });


        tv_wechat.setOnClickListener(v -> {
//            String a=sellGoodHistory.getTotalMoneyAfterDiscount();
//            BigDecimal  aa= XMathUtil.multiply(new BigDecimal(a),new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);;
////            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"sale\", \"params\": { \"tid\": \"VCMSPXUSIS0\", \"currency\": \"GBP\", \"amount\":"+aa+" },\"id\": 0 }";
//            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"sale\", \"params\": { \"tid\": \"VCMSPXUSIS0\", \"currency\": \"GBP\", \"amount\": 1000000 },\"id\": 0 }";
//            if(MyApplication.getInstance().getWebSocketClient().isOpen()){
//                webSocketClient.send(str);
//                showDialog3();
//            }
        });

    }

    private void print(int times,String orderCode,String time,String giveCash, String changestr,String payMethod) {
        if (pos_usb == null) {
            Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Please connect the printer", Toast.LENGTH_LONG).show();
            return;
        }
        String a = PrintUtil4.printxx(soldGoodDetailList);
//            System.out.print(a);
        if(!TextUtils.isEmpty(sellGoodHistory.getCustomerCode())){
            printText(2,"Table"+sellGoodHistory.getCustomerCode(), 1, 1, 20);
        }

//        printText("------------" + times + "-----------", 1, 1, 20);
        printText("Golden Mayfair Chinese Restaurant", 1, 1, 20);
        printText("3 West Road", 1, 0, 20);
        printText("Westcliff-on-Sea, Essex,SS0 9AU", 1, 0, 20);
        printText("Telephone 01702352707", 1, 0, 20);
//        printText("VAT No 320498217", 1, 0, 20);
        printText("", 0, 0);
        printText("Order Ref: " + orderCode, 0, 1);
        printText("------------------------------------------", 0, 0);
//            printText("Description                          Total", 0, 0);
//            printText("------------------------------------------", 0, 0);
        printText(a, 0, 1);
        printText("Total                                " + sellGoodHistory.getTotalMoney(), 0, 0);
        printText("------------------------------------------", 0, 0);
        printText("YOU SAVED  " + Double.valueOf(soldGoodDetailList.get(0).getDiscount())+"%OFF", 1, 1, 10);
        printText("------------------------------------------", 0, 0);
        printText("Grand Total                          " + sellGoodHistory.getTotalMoneyAfterDiscount(), 0, 1);
        printText("------------------------------------------", 0, 0);
        printText("Number Of Items                        " + sellGoodHistory.getTotalNumber() + "\n", 0, 1);
        printText("VAT Summary Breakdown", 1, 3, 30);
        printText("Total      VAT Value", 1, 1, 20);
        printText(sellGoodHistory.getTotalMoneyAfterDiscount() + "         " + sellGoodHistory.getTotalVat(), 1, 0, 20);
        printText("Payment Details\n", 0, 3);
//        printText("Paid By Cash                         " + giveCash, 0, 1, 20);
        printText("Paid By "+payMethod+"                         " + giveCash, 0, 1, 20);
        printText("Change                               " + changestr, 0, 1, 20);
        printText("You have been Served By" + MyApplication.UserName, 1, 0, 20);
        printText("Till No:" + "Till"+MyApplication.getInstance().getMachineId(), 0, 1, 10);
        printText("", 1, 1, 10);
        printBar(orderCode);
        printText(time, 1, 1, 20);
        printText("Please Keep for your records", 1, 0, 20);
        printText("Published Terms and Conditions Apply", 1, 0, 20);
        cutPaper();

        List<SoldGoodDetail> hotGoods=new ArrayList<>();

        for(SoldGoodDetail hotGood :soldGoodDetailList){
            if(hotGood.getHot_goods().equals("true")){
                hotGoods.add(hotGood);
            }else {

            }

        }
        if(hotGoods.size()!=0){
            printText(PrintUtil4.printxx(hotGoods), 0, 0);
            cutPaper();
        }

    }


    public void go(SellGoodHistory sellGoodHistory) {
        this.sellGoodHistory = sellGoodHistory;
        soldGoodDetailList.clear();
        soldGoodDetailList.addAll(sellGoodHistory.getSoldGoodDetailList());
        recyclerView.getAdapter().notifyDataSetChanged();
        tv_totalmoney.setText("£" + sellGoodHistory.getTotalMoneyAfterDiscount());
        tv_totalvat.setText("£" + sellGoodHistory.getTotalVat());
        tv_discount.setText("-£" + sellGoodHistory.getTotalSave());
        tv_discount.setOnClickListener(v -> {
//            Toast.makeText(getContext(), "ss", Toast.LENGTH_SHORT).show();
        });

//        myPresentation.setData(soldGoodDetailList);

    }


//    private void showDisplayByDisplayManager() {
//        DisplayManager displayManager = (DisplayManager) getContext().getSystemService(Context.DISPLAY_SERVICE);
//        Display[] displays = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION);
//        if (displays.length > 0) {
//            Display display = displays[0];
//            if (display != null) {
//                myPresentation = new MyPresentation(getContext(), display);
//                myPresentation.show();
//            }
//        } else {
//            Toast.makeText(getContext(), "Not Found Second Screen!", Toast.LENGTH_SHORT).show();
//        }
//
//
//    }


    private void showDialog2(String giveCash, String changestr) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_good_pay_change, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm = view.findViewById(R.id.tv_confirm);

        TextView tv_change = view.findViewById(R.id.tv_change);
        tv_change.setText("£" + changestr);


        tv_confirm.setOnClickListener(v -> {
            dialog.dismiss();
            dialogA.dismiss();
            MyApplication.getInstance().openCashDrawer();
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-" + MyApplication.MachineId + "-HHmmss");
            SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            String str = dateFormat.format(date);
            String str2 = dateFormat2.format(date);
            long paytime=getSecondTimestamp(date);
            print(1,str,str2,giveCash, changestr,"Cash");
//            print(2,str,str2,giveCash, changestr,"Cash");
//            print(3,str,str2,giveCash, changestr,"Cash");
            bt_finish.setVisibility(View.VISIBLE);
            bt_return.setVisibility(View.INVISIBLE);
            hiddenButton();
            //状态0 方式1

            ;
            List<SellGoodHistory> s=sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.CustomerCode.eq(sellGoodHistory.getCustomerCode())
                    ,SellGoodHistoryDao.Properties.PayStatus.eq(3)).list();
            if(s.size()>0){
                sellGoodHistoryDao.delete(s.get(0));
            }


            saveSellHistory(str,giveCash,changestr,0,paytime,1,"现金支付");



        });

        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            dialog.dismiss();
        });

    }

    private void saveSellHistory(String orderCode,String actualPayMoney,String changeMoney,int payStatus,long payTime,int paymentMethod,String result ) {

        sellGoodHistory.setOrderCode(orderCode);
        sellGoodHistory.setActualPayMoney(actualPayMoney);
        sellGoodHistory.setChangeMoney(changeMoney);
        sellGoodHistory.setPayStatus(payStatus);
        sellGoodHistory.setPayTime(payTime);
        sellGoodHistory.setPaymentMethod(paymentMethod);
        sellGoodHistory.setPayResult(result);

        Long id = sellGoodHistoryDao.insert(sellGoodHistory);
        List<SoldGoodDetail> soldGoodDetails = sellGoodHistory.getSoldGoodDetailList();
        for (SoldGoodDetail soldGoodDetail : soldGoodDetails) {
            soldGoodDetail.setSellGoodHistoryId(id);
        }
        soldGoodDetailDao.insertInTx(soldGoodDetails);

//        sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.CustomerCode.eq(false)).list();
//
//        sellGoodHistoryDao.delete();




        List<SellGoodHistory> sellGoodHistories2 = sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.PortSuccess.eq(false)).list();



        for(SellGoodHistory sellGoodHistory2:sellGoodHistories2){
            sellGoodHistory2.getSoldGoodDetails();
            getCoupons2(MyApplication.api_token,sellGoodHistory2);
        }










    }


    void getCoupons2(String api_token,SellGoodHistory sellGoodHistory2) {
        Gson gson = new Gson();
        String as = gson.toJson(sellGoodHistory2);
        RetrofitUtil.getInstance().getCoupons2(new ProgressSubscriber<>(a -> {

            sellGoodHistory2.setPortSuccess(true);
            sellGoodHistoryDao.update(sellGoodHistory2);

        }, getActivity()), api_token, as);
    }


    private void showDialog() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_good_pay, null, false);
        dialogA = new AlertDialog.Builder(getContext()).setView(view).create();
        dialogA.setCanceledOnTouchOutside(false);
        dialogA.show();
        dialogA.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView bt1, bt2, bt3;
        EditText editText;
        bt1 = view.findViewById(R.id.bt1);
        bt2 = view.findViewById(R.id.bt2);
        bt3 = view.findViewById(R.id.bt3);
        editText = view.findViewById(R.id.et_search);

        double a = Math.ceil(Double.parseDouble(sellGoodHistory.getTotalMoneyAfterDiscount()));
        editText.setText(sellGoodHistory.getTotalMoneyAfterDiscount());
        BigDecimal b = XMathUtil.add(a, 1).setScale(2, BigDecimal.ROUND_DOWN);
        BigDecimal c = XMathUtil.add(a, 2).setScale(2, BigDecimal.ROUND_DOWN);
        bt1.setText("£" + BigDecimal.valueOf(a).setScale(2, BigDecimal.ROUND_DOWN));
        bt2.setText("£" + b);
        bt3.setText("£" + c);
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        TextView tv_error = view.findViewById(R.id.textView11);


        bt1.setOnClickListener(v -> {
            bt1.setBackgroundResource(R.drawable.shape_green);
            bt2.setBackgroundResource(R.drawable.shape_gray);
            bt3.setBackgroundResource(R.drawable.shape_gray);
            editText.setText(a + "");
        });

        bt2.setOnClickListener(v -> {
            bt2.setBackgroundResource(R.drawable.shape_green);
            bt1.setBackgroundResource(R.drawable.shape_gray);
            bt3.setBackgroundResource(R.drawable.shape_gray);
            editText.setText(b + "");
        });

        bt3.setOnClickListener(v -> {
            bt3.setBackgroundResource(R.drawable.shape_green);
            bt2.setBackgroundResource(R.drawable.shape_gray);
            bt1.setBackgroundResource(R.drawable.shape_gray);
            editText.setText(c + "");
        });


        tv_confirm.setOnClickListener(v -> {
            String aa = editText.getText().toString();
            BigDecimal bigDecimal = new BigDecimal(aa.trim());
            BigDecimal bigDecimal2 = new BigDecimal(sellGoodHistory.getTotalMoneyAfterDiscount());

            if (bigDecimal.compareTo(bigDecimal2) > -1) {
                BigDecimal bb = XMathUtil.subtract(bigDecimal, bigDecimal2).setScale(2, BigDecimal.ROUND_DOWN);
                showDialog2(aa, bb + "");
            } else {
                tv_error.setVisibility(View.VISIBLE);
                tv_error.setText("Error:");
            }


        });

        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            dialogA.dismiss();
        });

    }


    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            Gson gson = new Gson();
            Log.d(TAG, msg.obj.toString());

            try {
                JSONObject jsonObject=new JSONObject(msg.obj.toString());
                if(jsonObject.has("method")){
                    SocketLogBean socketLogBean = gson.fromJson(msg.obj.toString(), SocketLogBean.class);
                    if(socketLogBean.getMethod().equals("signatureVerificationRequest")){
                        tv_msg.setText("Please Waiting");
                        long id=socketLogBean.getId();
                        showDialog5("Please check the Signature of the card!",id);
                    }else {
                        tv_msg.setText(socketLogBean.getParams().getNotificationValue());
                    }

                }else if(jsonObject.has("result")){
                    SocketSuccessBean socketSuccessBean = gson.fromJson(msg.obj.toString(), SocketSuccessBean.class);
                    String m=socketSuccessBean.getResult().getTransactionResult();
                    tv_msg.setText(socketSuccessBean.getResult().getTransactionResult());


                    if(m.equals("TIMED_OUT")){
                        tv_msg.setText("Sorry response from Car Machine is time Out!");
                        tv_confirm_card.setText("Manual Confirm");
                        tv_cancel_card.setText("Manual Cancel");
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.VISIBLE);
                        tv_confirm_card.setOnClickListener(v -> {
                            showDialog4("Are you sure to Manual Confirm?",1);
                        });
                        tv_cancel_card.setOnClickListener(v -> {
                            showDialog4("Are you sure Manual Cancel?",2);
                        });

                    }else if(m.equals("SUCCESSFUL")){
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.INVISIBLE);
                        String cardresult=msg.obj.toString();
                        tv_confirm_card.setOnClickListener(v -> {
                            cardDialog.dismiss();



                            printCard(cardresult);
                        });


                    }else if(m.equals("UNSUCCESSFUL")){
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.VISIBLE);
                        tv_confirm_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
//                            printCard()
                        });
                        tv_cancel_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
                        });
                    }else {
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.VISIBLE);
                        tv_confirm_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
//                            printCard()
                        });
                        tv_cancel_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
                        });
                    }









                }else if(jsonObject.has("error")) {
                    SocketErrorBean socketErrorBean = gson.fromJson(msg.obj.toString(), SocketErrorBean.class);
                    tv_msg.setText("Card Machine Error:"+socketErrorBean.getError().getMessage());
                    tv_confirm_card.setVisibility(View.VISIBLE);
                    tv_confirm_card.setText("Manual Confirm");
                    tv_cancel_card.setVisibility(View.INVISIBLE);
                    tv_confirm_card.setOnClickListener(v -> {
//                        cardDialog.dismiss();

                        tv_msg.setText("Please switch to Manually Mode!");
                        tv_confirm_card.setText("Manual Confirm");
                        tv_cancel_card.setText("Manual Cancel");
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.VISIBLE);
                        tv_confirm_card.setOnClickListener(v2 -> {
                            showDialog4("Are you sure to Manual Confirm?",1);
                        });
                        tv_cancel_card.setOnClickListener(v2 -> {
                            showDialog4("Are you sure Manual Cancel?",2);
                        });




                    });
                    tv_cancel_card.setOnClickListener(v -> {
                        cardDialog.dismiss();
                    });
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return true;
        }
    });

    private void printCard(String result) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-" + MyApplication.MachineId + "-HHmmss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

        String str = dateFormat.format(date);
        String str2 = dateFormat2.format(date);
        long paytime=getSecondTimestamp(date);
        print(1,str,str2,sellGoodHistory.getTotalMoneyAfterDiscount(), "0.00","Card");
//        print(2,str,str2,sellGoodHistory.getTotalMoneyAfterDiscount(), "0.00","Card");
//        print(3,str,str2,sellGoodHistory.getTotalMoneyAfterDiscount(), "0.00","Card");
        bt_finish.setVisibility(View.VISIBLE);
        bt_return.setVisibility(View.INVISIBLE);
        hiddenButton();
        //状态0 方式1
        saveSellHistory(str,sellGoodHistory.getTotalMoneyAfterDiscount(), "0.00",0,paytime,2,result);
    }


    private void showDialog3() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_waiting, null, false);
        cardDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        cardDialog.setCanceledOnTouchOutside(false);
        cardDialog.show();
        cardDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        tv_confirm_card = view.findViewById(R.id.tv_confirm);
        tv_cancel_card = view.findViewById(R.id.tv_cancel);
////        tv_confirm_card.setVisibility(View.VISIBLE);
        tv_msg = view.findViewById(R.id.tv_change);
//
//        tv_cancel_card.setOnClickListener(v -> {
//            cardDialog.dismiss();
//        });

        tv_msg.setText("Sorry response from Car Machine is time Out!");
        tv_confirm_card.setText("Manual Confirm");
        tv_cancel_card.setText("Manual Cancel");
        tv_confirm_card.setVisibility(View.VISIBLE);
        tv_cancel_card.setVisibility(View.VISIBLE);
        tv_confirm_card.setOnClickListener(v -> {
            showDialog4("Are you sure to Manual Confirm?",1);
        });
        tv_cancel_card.setOnClickListener(v -> {
            showDialog4("Are you sure Manual Cancel?",2);
        });


    }


    private void showDialog4(String str,int f) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        timeoutDialog.setCanceledOnTouchOutside(false);
        timeoutDialog.show();
        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);

        tv_msg.setText(str);




        tv_cancel_card.setOnClickListener(v -> {
            if(f==1){
                timeoutDialog.dismiss();
            }else if(f==2){
                timeoutDialog.dismiss();
            }else {
                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": "+id+", \"result\": { \"accepted\": false } }";
                if(MyApplication.getInstance().getWebSocketClient().isOpen()){
                    MyApplication.getInstance().getWebSocketClient().send(str22);
                    timeoutDialog.dismiss();
                }
            }

        });

        tv_confirm_card.setOnClickListener(v -> {
            if(f==1){
                printCard("手动确认成功");
                timeoutDialog.dismiss();
                if(cardDialog!=null){
                    cardDialog.dismiss();
                }

            }else if(f==2){
                timeoutDialog.dismiss();
                if(cardDialog!=null){
                    cardDialog.dismiss();
                }
//                cardDialog.dismiss();
            }else {
//                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": 0, \"result\": { \"accepted\": true } }";
                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": "+id+", \"result\": { \"accepted\": true } }";
                if(MyApplication.getInstance().getWebSocketClient().isOpen()){
                    MyApplication.getInstance().getWebSocketClient().send(str22);
                    timeoutDialog.dismiss();
                }
            }

        });

    }


    private void showDialog5(String str,long id) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        timeoutDialog.setCanceledOnTouchOutside(false);
        timeoutDialog.show();


        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                timeoutDialog.dismiss();
                //结束本界面并跳转到收派员列表的界面
                t.cancel();
            }
        }, 60000);






        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);

        tv_msg.setText(str);





        tv_cancel_card.setOnClickListener(v -> {
                t.cancel();
                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": "+id+", \"result\": { \"accepted\": false } }";
                if(MyApplication.getInstance().getWebSocketClient().isOpen()){
                    MyApplication.getInstance().getWebSocketClient().send(str22);
                    timeoutDialog.dismiss();}


        });

        tv_confirm_card.setOnClickListener(v -> {
            t.cancel();
//                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": 0, \"result\": { \"accepted\": true } }";
                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": "+id+", \"result\": { \"accepted\": true } }";
                if(MyApplication.getInstance().getWebSocketClient().isOpen()){
                    MyApplication.getInstance().getWebSocketClient().send(str22);
                    timeoutDialog.dismiss();
                }


        });

    }


    private void showDialogError() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_error, null, false);
        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        timeoutDialog.setCanceledOnTouchOutside(false);
        timeoutDialog.show();
        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);





        tv_cancel_card.setOnClickListener(v -> {

                    timeoutDialog.dismiss();


        });

        tv_confirm_card.setOnClickListener(v -> {

                    timeoutDialog.dismiss();
                    showDialog7();

        });





    }

    private void showDialog7() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_waiting, null, false);
        Dialog cardDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        cardDialog.setCanceledOnTouchOutside(false);
        cardDialog.show();
        cardDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);
        tv_msg.setText("Please switch to Manually Mode!");
        tv_confirm_card.setText("Manual Confirm");
        tv_cancel_card.setText("Manual Cancel");
        tv_confirm_card.setVisibility(View.VISIBLE);
        tv_cancel_card.setVisibility(View.VISIBLE);
        tv_confirm_card.setOnClickListener(v2 -> {
            showDialog8("Are you sure to Manual Confirm?",1,cardDialog);
        });
        tv_cancel_card.setOnClickListener(v2 -> {
            showDialog8("Are you sure Manual Cancel?",2,cardDialog);
        });


    }




    private void showDialog8(String str,int f,Dialog dialog) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        timeoutDialog.setCanceledOnTouchOutside(false);
        timeoutDialog.show();
        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);

        tv_msg.setText(str);




        tv_cancel_card.setOnClickListener(v -> {
            if(f==1){
                timeoutDialog.dismiss();
                dialog.dismiss();
            }else if(f==2){
                timeoutDialog.dismiss();
                dialog.dismiss();
            }
        });

        tv_confirm_card.setOnClickListener(v -> {
            if(f==1){
                printCard("手动确认成功");
                timeoutDialog.dismiss();
                dialog.dismiss();
                if(cardDialog!=null){

                    cardDialog.dismiss();
                }

            }else if(f==2){
                timeoutDialog.dismiss();
                dialog.dismiss();
                if(cardDialog!=null){

                    cardDialog.dismiss();
                }
//                cardDialog.dismiss();
            }

        });

    }
}